import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Text,
    ListView,
    TouchableOpacity,
    TouchableHighlight,
    Animated,
    ToastAndroid
} from 'react-native';

import {PullList} from 'react-native-pull';
import MainListItem from '../communals/MainListItem.js';
import HttpUtils from '../http/HttpUtils.js';
import {screenWidth} from '../communals/MyExports.js';
import LoadingView from '../communals/LoadingView.js';
import RealmUtil from '../db/RealmUtil.js';

/**
 * 小时风云榜页面
 * Created by 10691 on 17/5/8.
 */
export default class HourList extends Component {

    constructor() {
        super();
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
            isShowLoadingView: true,
            // 时间段
            timeSlot: '',
            // 根据hasnexthour字段判断下一小时按钮状态
            isNextTouch: false
        };

        this.nexthourhour = '';
        this.nexthourdate = '';
        this.lasthourhour = '';
        this.lasthourdate = '';
        this.loadData = this.loadData.bind(this);
        this.renderRow = this.renderRow.bind(this);
    }

    componentDidMount() {
        this.loadData()
    }

    /**
     *数据加载
     */
    loadData(date, hour) {
        let pullList = this.refs.pullList;
        if (pullList) {
            pullList.scrollTo({y: 0});
            // 执行下拉刷新动画
            pullList.state.pullPan = new Animated.ValueXY({x: 0, y: this.topIndicatorHeight * -1});
        }
        let params;
        if (date) {
            params = {
                'date': date,
                'hour': hour,
            };
        }
        HttpUtils.get('http://guangdiu.com/api/getranklist.php', params).then((responseData) => {

            let isNextTouch = true;
            if (responseData.hasnexthour === '1') {    // hasnexthour不为0时 下一小时 按钮可点击
                isNextTouch = false;
            }

            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(responseData.data),
                isShowLoadingView: false,
                timeSlot: responseData.displaydate + responseData.rankhour + '点档(' + responseData.rankduring + ')',
                isNextTouch: isNextTouch,    // 更新按钮状态
            });

            // 关闭刷新动画
            if (pullList) {
                setTimeout(() => {
                    pullList.resetDefaultXYHandler();
                }, 1000);
            }

            this.nexthourhour = responseData.nexthourhour;
            this.nexthourdate = responseData.nexthourdate;
            this.lasthourhour = responseData.lasthourhour;
            this.lasthourdate = responseData.lasthourdate;

            // 清除本地存储的数据
            RealmUtil.removeAllData('HourListData');

            // 存储数据到本地
            RealmUtil.create('HourListData', responseData.data);
        }).catch((error) => {
            console.log(error);

            // 拿到本地存储的数据,展示出来,如果没有存储,那就显示无数据页面
            ToastAndroid.show("执行错误", ToastAndroid.SHORT);
            this.data = RealmUtil.loadAll('HourListData');
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(this.data),
            });

        });
    }

    render() {
        return (
            <View style={HourListStyles.containerStyle}>
                {/*顶部时间段*/}
                <Text style={HourListStyles.headerStyle}>{this.state.timeSlot}</Text>
                {/*列表*/}
                {this.renderListView()}
                {/*底部操作栏*/}
                <View style={HourListStyles.operationViewStyle}>
                    <TouchableOpacity
                        onPress={() => this.loadLastHour()}>
                        <Text style={HourListStyles.operationTextStyle}>{'<' + '上一小时  '}</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                        onPress={() => this.loadNextHour()}
                        disabled={this.state.isNextTouch}>
                        <Text
                            style={[HourListStyles.operationTextStyle, {color: this.state.isNextTouch === false ? 'green' : 'gray'}]}>{'  下一小时' + '>'}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    /**
     * 加载上一个小时的内容列表
     */
    loadLastHour() {
        this.loadData(this.lasthourdate, this.lasthourhour);
    }

    /**
     * 加载下一个小时的内容列表
     */
    loadNextHour() {
        this.loadData(this.nexthourdate, this.nexthourhour);
    }

    /**
     *渲染列表ListView
     */
    renderListView() {
        if (this.state.isShowLoadingView) {
            return (
                <View style={{flex: 1}}>
                    <LoadingView/>
                </View>
            );
        } else {
            return <PullList
                ref='pullList'
                removeClippedSubviews={false}
                onPullRelease={() => this.loadData()}
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                initialListSize={5}
                style={HourListStyles.listViewStyle}/>
        }
    }

    /**
     * 返回每一个Item
     * @param rowData
     * @returns {XML}
     */
    renderRow(rowData) {
        return (
            <TouchableHighlight
                underlayColor={'#13fff0'}
                onPress={() => {
                    this.props.navigation.navigate('CommunalDetail', {ID: rowData.id});
                }}>
                <View>
                    <MainListItem
                        image={rowData.image}
                        title={rowData.title}
                        mall={rowData.mall}
                        pubTime={rowData.pubtime}
                        fromSite={rowData.fromsite}/>
                </View>
            </TouchableHighlight>
        );
    }

}

const HourListStyles = StyleSheet.create({

    containerStyle: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },

    headerStyle: {
        width: screenWidth,
        height: 45,
        textAlign: 'center',
        lineHeight: 35,
        fontSize: 15,
    },

    operationViewStyle: {
        width: screenWidth,
        height: 45,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },

    operationTextStyle: {
        color: 'green',
        fontWeight: 'bold',
        fontSize: 15,
    },

    listViewStyle: {
        width: screenWidth,
    },
});